<template>
  <div class="item">
    <div class="title">行车号:{{ craneInfo.craneNo }}</div>
    <div class="content">
      <div class="craneData data1">
        <div class="ch"><span :style="{ backgroundColor: craneInfo.ready === 1 ? 'green' : 'red' }"></span>准备</div>
        <div class="ch">
          <span :style="{ backgroundColor: craneInfo.powerStatus === 1 ? 'green' : 'red' }"></span>上电
        </div>
        <div class="ch"><span :style="{ backgroundColor: craneInfo.askPlan === 1 ? 'green' : 'red' }"></span>请求</div>
        <div class="ch">
          <span :style="{ backgroundColor: craneInfo.taskExecuting === 1 ? 'green' : 'red' }"></span>执行
        </div>
        <div class="ch"><span :style="{ backgroundColor: craneInfo.isEmpty === 1 ? 'green' : 'red' }"></span>载重</div>
        <div class="ch">
          <span>{{ craneInfo.controlMode }}</span
          >{{ controlModel_ch }}
        </div>
      </div>
      <div class="craneData data2">
        <!-- craneInfo.orderId -->
        <div class="ch"><span>指令号</span>{{ craneInfo.orderId }}</div>
        <div class="ch"><span>当前X</span>{{ craneInfo.xAct }}</div>
        <div class="ch"><span>当前Y</span>{{ craneInfo.yAct }}</div>
        <div class="ch"><span>当前Z</span>{{ craneInfo.zAct }}</div>
        <div class="ch"><span>动作标记</span>{{ craneInfo.craneStatus }}</div>
        <div class="ch"><span>急停状态</span>{{ craneInfo.emgStop }}</div>
        <div class="ch">
          <span>起吊角度</span>{{ craneInfo.planUpAngle }}
        </div>
        <div class="ch">
          <span>卸下角度</span>{{ craneInfo.planDownAngle }}
        </div>
        <div class="ch"><span>旋转角度</span>{{ craneInfo.rotateAngleAct }}</div>
      </div>
      <div class="craneData data2">
        <div class="ch">
          <span>起吊位</span>{{ craneInfo.fromStockNo }}
        </div>
        <div class="ch">
          <span>卸下位</span>{{ craneInfo.toStockNo }}
        </div>
         <div class="ch"><span>卷号</span>{{ craneInfo.matNo }}</div>
        <div class="ch"><span>X速度</span>{{ craneInfo.xSpeed }}</div>
        <div class="ch"><span>Y速度</span>{{ craneInfo.ySpeed }}</div>
        <div class="ch"><span>Z速度</span>{{ craneInfo.zSpeed }}</div>
        <div class="ch"><span>防摇角度X</span>{{ craneInfo.angleX }}</div>
        <div class="ch"><span>防摇角度Y</span>{{ craneInfo.angleY }}</div>
        <div class="ch"><span>防摇水平X</span>{{ craneInfo.gradientX }}</div>
        <div class="ch"><span>防摇水平Y</span>{{ craneInfo.gradientY }}</div>
      </div>
      <div class="craneData data3">
        <div class="ch">
          <span class="name">起吊X</span>
          <span class="value">{{ craneInfo.planUpX }}</span>
          <input type="text" v-model="commitData.planUpX" />
          <button @click="handleToNine('planUpX')">9</button>
        </div>
        <div class="ch">
          <span class="name">起吊Y</span>
          <span class="value">{{ craneInfo.planUpY }}</span>
          <input type="text" v-model="commitData.planUpY" />
          <button @click="handleToNine('planUpY')">9</button>
        </div>
        <div class="ch">
          <span class="name">起吊Z</span>
          <span class="value">{{ craneInfo.planUpZ }}</span>
          <input type="text" v-model="commitData.planUpZ" />
          <button @click="handleToNine('planUpZ')">9</button>
        </div>
        <div class="ch">
          <span class="name">卸下X</span>
          <span class="value">{{ craneInfo.planDownX }}</span>
          <input type="text" v-model="commitData.planDownX" />
          <button @click="handleToNine('planDownX')">9</button>
        </div>
        <div class="ch">
          <span class="name">卸下Y</span>
          <span class="value">{{ craneInfo.planDownY }}</span>
          <input type="text" v-model="commitData.planDownY" />
          <button @click="handleToNine('planDownY')">9</button>
        </div>
        <div class="ch">
          <span class="name">卸下Z</span>
          <span class="value">{{ craneInfo.planDownZ }}</span>
          <input type="text" v-model="commitData.planDownZ" />
          <button @click="handleToNine('planDownZ')">9</button>
        </div>
        <div class="ch">
          <span class="name">钢卷内径</span>
          <span class="value">{{ craneInfo.currentMatInternalDiameter }}</span>
          <input type="text" v-model="commitData.matLength" />
          <button @click="handleToNine('matLength')">9</button>
        </div>
        <div class="ch">
          <span class="name">钢卷宽度</span>
          <span class="value">{{ craneInfo.currentMatWidth }}</span>
          <input type="text" v-model="commitData.matWidth" />
          <button @click="handleToNine('matWidth')">9</button>
        </div>
        <div class="ch">
          <span class="name">钢卷外径</span>
          <span class="value">{{ craneInfo.currentMatDiameter }}</span>
          <input type="text" v-model="commitData.matThickness" />
          <button @click="handleToNine('matThickness')">9</button>
        </div>
      </div>
    </div>
    <div class="operation">
      <q-btn-dropdown color="primary" label="更多">
        <q-list>
          <q-item clickable v-close-popup @click="handleOpr('校准角度')">
            <q-item-section>
              <q-item-label>校准角度</q-item-label>
            </q-item-section>
          </q-item>
          <q-item clickable v-close-popup @click="handleOpr('校准高度')">
            <q-item-section>
              <q-item-label>校准高度</q-item-label>
            </q-item-section>
          </q-item>
          <q-item clickable v-close-popup @click="handleOpr('大车倾角校准')">
            <q-item-section>
              <q-item-label>大车倾角校准</q-item-label>
            </q-item-section>
          </q-item>
          <q-item clickable v-close-popup @click="handleOpr('小车倾角校准')">
            <q-item-section>
              <q-item-label>小车倾角校准</q-item-label>
            </q-item-section>
          </q-item>
        </q-list>
      </q-btn-dropdown>
      <q-btn color="secondary" label="上电" @click="handleOpr('上电')" />
      <q-btn color="secondary" label="切自动" @click="handleOpr('切自动')" />
      <q-btn color="primary" label="切远程" @click="handleOpr('切远程')" />
      <q-btn color="amber" glossy label="复位" @click="handleOpr('复位')" />
      <q-btn color="primary" label="发送" @click="handleSend" />
    </div>

    <div class="alarm-tabs">
      <q-btn-toggle
        v-model="activeAlarmTab"
        :options="[
          { label: '行车报警', value: 'crane' },
          { label: 'WMS报警', value: 'wms' }
        ]"
        spread
        no-caps
        unelevated
      />
    </div>

    <div class="errCodeInfo" v-if="activeAlarmTab === 'crane'">
      <div class="errorItem" v-for="i in 10" :key="i">
        报警[{{ craneInfo[`errCode${i}`] || '' }}]：{{ craneInfo[`errMsg${i}`] || '' }}
      </div>
    </div>

    <div class="errCodeInfo" v-if="activeAlarmTab === 'wms'">
      <div class="errorItem" v-for="(alarm, index) in displayedAlarms" :key="index">
        {{ (alarm?.createTime || '') + ' ' + (alarm?.content || '') }}
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, computed, PropType, watch } from 'vue';
import { api } from 'src/boot/api';
import { useQuasar } from 'quasar';

import { CraneProps } from './model';

export default defineComponent({
  name: 'crane-self',

  props: {
    craneInfo: {
      type: Object as PropType<CraneProps>,
      required: true,
    },
  },

  setup(props) {
    const $q = useQuasar();
    const commitData = ref({
      craneNo: '',
      planUpX: '',
      planUpY: '',
      planUpZ: '',
      planDownX: '',
      planDownY: '',
      planDownZ: '',
      planUpAngle: '',
      planDownAngle: '',
      matLength: '',
      matWidth: '',
      matThickness: '',
      shortCmd: '',
      keyWord: '',
    });

    const activeAlarmTab = ref('crane');
    const wmsAlarms = ref([]);
    const isLoading = ref(false);

    onMounted(() => {
      commitData.value.craneNo = props.craneInfo.craneNo;
    });

    const controlModel_ch = computed(() => {
      switch (props.craneInfo.controlMode) {
        case 1:
          return '遥控';
        case 2:
          return '手动';
        case 4:
          return '自动';
        case 5:
          return '远程';
        default:
          return '';
      }
    });

    //封9
    const handleToNine = (
      field:
        | 'planUpX'
        | 'planUpY'
        | 'planUpZ'
        | 'planDownX'
        | 'planDownY'
        | 'planDownZ'
        | 'planUpAngle'
        | 'planDownAngle'
        | 'matLength'
        | 'matWidth'
        | 'matThickness',
    ) => {
      commitData.value[field] = '999999';
    };

    const handleOpr = (field: string) => {
      switch (field) {
        case '上电':
          commitData.value.shortCmd = '80';
          break;
        case '切自动':
          commitData.value.shortCmd = '400';
          break;
        case '切远程':
          commitData.value.shortCmd = '500';
          break;
        case '复位':
          commitData.value.shortCmd = '300';
          break;
        case '校准角度':
          commitData.value.shortCmd = '30';
          break;
        case '校准高度':
          commitData.value.shortCmd = '20';
          break;
        case '大车倾角校准':
          commitData.value.shortCmd = '60';
          break;
        case '小车倾角校准':
          commitData.value.shortCmd = '61';
          break;
        default:
          return;
      }

      $q.dialog({
        title: '确认',
        message: `确定要执行[${field}]操作吗？`,
        cancel: {
          label: '取消',
          flat: true,
        },
        ok: {
          label: '确认',
          flat: true,
        },
        persistent: true,
      }).onOk(async () => {
        try {
          const { code, message } = await api.post('/craneService/sendCraneOrder', 
             {
              ...commitData.value,
              craneNo: props.craneInfo.craneNo // Ensure craneNo is properly set
            } 
          );
          
          if (code === 200) {
            $q.notify({ 
              message: `${field}操作成功`,
              type: 'positive',
              timeout: 3000 
            });
          } else {
            $q.notify({ 
              message: message || `${field}操作失败`,
              type: 'negative',
              timeout: 3000 
            });
          }
        } catch (error) {
          console.error('Operation failed:', error);
          $q.notify({ 
            message: `${field}操作失败: ${error.message || '未知错误'}`,
            type: 'negative',
            timeout: 3000 
          });
        }
      });
    };

    const handleSend = () => {
      if (props.craneInfo.ready !== 0 && props.craneInfo.controlMode == 4 && props.craneInfo.askPlan !== 0) {
        $q.dialog({
          title: '请确认库区是否有人？',
          message: '请填写操作日志:',
          prompt: {
            model: '',
            type: 'text',
          },
          cancel: {
            label: '取消',
            flat: true,
          },
          ok: {
            label: '确认',
            flat: true,
          },
          persistent: true,
        }).onOk(async keyWord => {
          commitData.value.shortCmd = '1';
          commitData.value.keyWord = keyWord;

           const { code, message } = await api.post('/craneService/sendCraneOrder',   commitData.value );
           console.log('Response:', { code, message });
           $q.notify({ message: '操作成功', timeout: 3000 });
       
           
        });
      } else {
        $q.notify({ message: '准备，自动，请求状态不正确', timeout: 3000, color: 'negative' });
      }
    };

    const fetchWmsAlarms = async () => {
      try {
        const { data } = await api.get('/alarmService/fuzzyQueryAlarmHistoryList', {
          timeout: 15000  // 设置为15秒
        });
        wmsAlarms.value = data?.slice(0, 10) || [];
      } catch (error) {
        console.error('Failed to fetch WMS alarms:', error);
        $q.notify({ 
          message: '获取报警信息失败，请稍后重试',
          type: 'warning',
          timeout: 3000 
        });
      }
    };

    const fetchWmsAlarmsWithLoading = async () => {
      isLoading.value = true;
      try {
        await fetchWmsAlarms();
      } finally {
        isLoading.value = false;
      }
    };

    watch(activeAlarmTab, (newValue) => {
      if (newValue === 'wms') {
        fetchWmsAlarmsWithLoading();
      }
    });

    const displayedAlarms = computed(() => {
      // 如果报警内容平均长度较长，则显示较少行数
      const avgContentLength = wmsAlarms.value.reduce((sum, alarm) => 
        sum + ((alarm?.content?.length || 0) + (alarm?.createTime?.length || 0)), 0) / 
        (wmsAlarms.value.length || 1);
      
      // 根据内容长度动态决定显示行数
      let displayCount = 10; // 默认显示10行
      
      if (avgContentLength > 100) {
        displayCount = 3; // 内容非常长时显示3行
      } else if (avgContentLength > 50) {
        displayCount = 5; // 内容较长时显示5行
      } else if (avgContentLength > 30) {
        displayCount = 7; // 内容中等长度时显示7行
      }
      
      // 获取实际报警数据
      const alarms = wmsAlarms.value.slice(0, displayCount);
      
      // 创建一个固定长度为10的数组
      const result = new Array(10).fill(null).map((_, index) => {
        // 如果有对应的报警数据，则使用该数据，否则返回空对象
        return index < alarms.length ? alarms[index] : { createTime: '', content: '' };
      });
      
      return result;
    });

    return { commitData, controlModel_ch, handleToNine, handleOpr, handleSend, activeAlarmTab, wmsAlarms, isLoading, displayedAlarms };
  },
});
</script>

<style scoped lang="scss">
.item {
  width: 770px;
  height: auto;
  margin-top: 40px;
  color: #fff;
  background-color: #313143;
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.37);
  .title {
    width: 100%;
    height: 40px;
    line-height: 40px;
    text-align: center;
    font-size: 20px;
    font-weight: bolder;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    background-color: rgb(103, 118, 222);
  }
  .content {
    display: flex;
    width: 100%;
    height: 290px;
    // min-height: 290px;
    .craneData {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
      padding: 8px 12px;
      .ch {
        width: 100%;
        display: flex;
        align-items: center;
        // justify-content: space-between;
        border: 1px solid grey;
      }
    }
    .data1 {
      width: 100px;
      height: 100%;
      border-right: 1px solid grey;
      text-indent: 4px;
      .ch {
        padding: 4px;
        span {
          width: 24px;
          height: 24px;
          border-radius: 50%;
        }
      }
    }
    .data2 {
      width: 190px;
      height: 100%;
      border-right: 1px solid grey;
      .ch {
        text-indent: 6px;
        overflow: hidden;
        span {
          width: 85px;
          padding-right: 8px;
          text-align: right;
          border-right: 1px solid grey;
        }
      }
    }
    .data3 {
      width: 290px;
      height: 100%;
      .ch {
        height: 28px;
        justify-content: space-between;
        padding: 0 4px;
        text-indent: 4px;
        span.name {
          width: 70px;
          text-align: right;
          padding-right: 8px;
          border-right: 1px solid grey;
        }
        span.value {
          width: 70px;
        }
        input {
          width: 70px;
          height: 20px;
          color: #fff;
          background-color: rgba(255, 255, 255, 0.1);
          border: 1px solid rgba(255, 255, 255, 0.2);
        }
        button {
          width: 30px;
          height: 24px;
          background-color: grey;
        }
      }
    }
  }
  .operation {
    display: flex;
    width: 100%;
    padding: 8px 0 12px;
    flex-wrap: nowrap;
    align-items: center;
    justify-content: space-around;
  }

  .alarm-tabs {
    padding: 8px 12px;
    
    :deep(.q-btn-toggle) {
      width: 100%;
      background: rgba(255, 255, 255, 0.05);
      
      .q-btn {
        color: #e0e0e0;
        
        &--active {
          background: rgba(255, 255, 255, 0.1);
        }
      }
    }
  }

  .errCodeInfo {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 450px;
    padding: 8px 12px;
    background-color: #313143;
    overflow-y: auto;

    .errorItem {
      width: 100%;
      padding: 8px 12px;
      margin-bottom: 4px;
      background: rgba(49, 49, 67, 1);
      border: 1px solid rgba(255, 255, 255, 0.2);
      border-radius: 4px;
      color: #e0e0e0;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
      white-space: normal;
      overflow: visible;
      line-height: 1.4;
      height: 40px;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      cursor: default;
    }
  }
}
</style>
